package com.hiltony.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Date;


/**
 * Created by YX on 2016/9/16.
 *
 */

@Controller
@RequestMapping("/weather")
public class WeatherController {

    @RequestMapping("/getWeatherInfo")
    public String getWeatherInfo(HttpServletRequest request, Model model){


        String urlnow = "https://api.thinkpage.cn/v3/weather/now.json?key=poamoss4vztmkrtq&location=hangzhou&language=zh-Hans&unit=c";

        String urlfor4day="https://api.thinkpage.cn/v3/weather/daily.json?key=poamoss4vztmkrtq&location=hangzhou&language=zh-Hans&unit=c&start=0&days=3";

        String urllife="https://api.thinkpage.cn/v3/life/suggestion.json?key=poamoss4vztmkrtq&location=hangzhou&language=zh-Hans";

        String result0 = getHttpsData(urlnow);
        String result1=getHttpsData(urlfor4day);
        String result2=getHttpsData(urllife);

        JSONObject now= (JSONObject) JSON.parse(result0);
        JSONObject for4day= (JSONObject) JSON.parse(result1);
        JSONObject life= (JSONObject) JSON.parse(result2);

        JSONArray nowArray = (JSONArray)now.get("results");
        JSONObject nowObject = (JSONObject) nowArray.get(0);
//        nowObject.get("now");

        JSONArray for4dayArray = (JSONArray)for4day.get("results");
        JSONObject for4dayObject = (JSONObject) for4dayArray.get(0);
//        for4dayObject.get("daily");

        JSONArray lifeArray = (JSONArray)life.get("results");
        JSONObject lifeObject = (JSONObject) lifeArray.get(0);
//        lifeObject.get("suggestion");

        JSONObject result = new JSONObject();
        result.put("now",nowObject.get("now"));
        result.put("daily",for4dayObject.get("daily"));
        result.put("suggestion",lifeObject.get("suggestion"));


//        return result.toJSONString();


        model.addAttribute("weather",result.toJSONString());

        System.out.println(result.toJSONString());
        return "weather/weather";

    }

    @RequestMapping("/getWeatherDate")
    @ResponseBody
    public String getWeatherDate() {
//        String weatherParam = getWeatherParam();

        String urlnow = "https://api.thinkpage.cn/v3/weather/now.json?key=poamoss4vztmkrtq&location=hangzhou&language=zh-Hans&unit=c";

//        String weatherParam2 = getWeatherParam();
//        String url2 = "https://api.thinkpage.cn/v3/life/suggestion.json?location=hangzhou " + "&" + weatherParam2;

        String urllife="https://api.thinkpage.cn/v3/life/suggestion.json?key=poamoss4vztmkrtq&location=hangzhou&language=zh-Hans";

        String result1=getHttpsData(urlnow);
        String result2=getHttpsData(urllife);

        JSONObject now= (JSONObject) JSON.parse(result1);
        JSONObject life= (JSONObject) JSON.parse(result2);

        JSONArray nowArray = (JSONArray)now.get("results");
        JSONObject nowObject = (JSONObject) nowArray.get(0);
        nowObject.get("now");

        JSONArray lifeArray = (JSONArray)life.get("results");
        JSONObject lifeObject = (JSONObject) lifeArray.get(0);
        lifeObject.get("suggestion");

        JSONObject result = new JSONObject();
        result.put("now",nowObject.get("now"));
        result.put("suggestion",lifeObject.get("suggestion"));

        return result.toJSONString();
    }


    private String getHttpsData(String url){

        String result = "";
        try {

            BufferedReader in;
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpsURLConnection conn;
            conn = (HttpsURLConnection) realUrl.openConnection();

            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            // 设置超时时间
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);
            // 建立实际的连接
            conn.connect();

            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += "\n" + line;
            }
            conn.disconnect();
//            System.out.println(result);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    private String getWeatherParam(){
        String HMAC_SHA1 = "HmacSHA1";
        Long timestamp=(new Date().getTime()/1000);
        String data="ts="+timestamp+"&ttl=10&uid=U11A6D2DB4";
        String key = "poamoss4vztmkrtq";
        SecretKeySpec signingKey;
        Mac mac;
        try {
            signingKey = new SecretKeySpec(key.getBytes("US-ASCII"), HMAC_SHA1);
            mac = Mac.getInstance(HMAC_SHA1);
            mac.init(signingKey);
            byte[] rawHmac = mac.doFinal(data.getBytes("US-ASCII"));
            byte[] encode= Base64.getUrlEncoder().encode(rawHmac);
            String result = new String(encode,"US-ASCII");
            String urlencode = URLEncoder.encode(result,"US-ASCII");

            System.out.println(data+"&sig="+urlencode);

            return data+"&sig="+urlencode;


        } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return "";
    }

}

